//
//  HomeInfoController.m
//  GuShiNews
//
//  Created by huachun on 2019/8/22.
//  Copyright © 2019 Jones. All rights reserved.
//

#import "HomeInfoController.h"
#import "HomeInfoTopheaderView.h"
#import "HomeAction.h"
#import "HomeInfoTCell.h"
#import "LunTanModel.h"
#import "GengTieView.h"
#import "LunCommentModel.h"
#import "HuaHereClass.h"
#import "GetLunCommnetVModel.h"
#import "TouPiaoButtomView.h"
#import "UserJubuViewModel.h"
#import "RootSuperAction.h"
#import "HJonesNetting.h"
#import "JoneCunChu.h"
#import "MementoCenter.h"
#import "NSObject+MementoCenter.h"

@interface HomeInfoController ()<GetLunCommentDelegate>{
    NSInteger page;
    
    BOOL Zan_ok;
    BOOL Bottom_ok;
    BOOL Like_OK;
}

@property (nonatomic, strong) UITableView *mytable;

@property (nonatomic, strong) TouPiaoButtomView *bottomview;

@property (nonatomic, strong) NSMutableArray     *Like_list;

@end

@implementation HomeInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=_Model.type;
    
    __weak __typeof(&*self)weakSelf = self;
    if ([UserModel info].userid) {
        if ([[UserModel info].userid isEqualToString:_Model.user_id]) {
            self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:[JonesButtonItem PublicBarButtonItemPian], [JonesButtonItem NavZiButton:@"删除" andaction:@selector(shanchu) andtarget:self andAlignment:0], nil];
        }else{
            self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:[JonesButtonItem PublicBarButtonItemPian], [JonesButtonItem NavImgButton:[UIImage imageNamed:@"news_more"] andaction:@selector(fabu) andtarget:self], nil];
        }
    }else{
        self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:[JonesButtonItem PublicBarButtonItemPian], [JonesButtonItem NavImgButton:[UIImage imageNamed:@"news_more"] andaction:@selector(fabu) andtarget:self], nil];
    }
    
    self.Data_array = [NSMutableArray new];
    LunCommentModel *model = [LunCommentModel new];
    model.userid = _Model.user_id;
    model.name = _Model.name;
    model.logo = _Model.logo;
    model.sex = _Model.sex;
    model.briday = _Model.briday;
    model.lcomment_info = _Model.info;
    model.lcomment_date = _Model.date;
    model.type = 0;
    model.Img_array = _Model.Img_array;
    if (_Model.Img_array.count>0) {
        model.Height = [HuaHereClass size:model.lcomment_info font:[UIFont systemFontOfSize:16] width:RECRWITCH-30 height:10000].height+10 + (RECRWITCH-40)/3 + 10;
    }else{
        model.Height = [HuaHereClass size:model.lcomment_info font:[UIFont systemFontOfSize:16] width:RECRWITCH-30 height:10000].height+10;
    }
    [self.Data_array addObject:model];
    
    _mytable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, RECRWITCH, RECERHEIGHT-(NAV_Height-20)) style:UITableViewStylePlain];
    _mytable.dataSource          = self;
    _mytable.delegate            = self;
    _mytable.backgroundColor     = backColor;
    _mytable.separatorInset      = UIEdgeInsetsMake(0, 15, 0, 0);
    _mytable.separatorStyle      = UITableViewCellSeparatorStyleNone;
    _mytable.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _mytable.emptyDataSetSource   = self;
    _mytable.emptyDataSetDelegate = self;
    [self.view addSubview:_mytable];
//    [_mytable registerClass:[HomeInfoTopheaderView class] forHeaderFooterViewReuseIdentifier:@"header"];
    _mytable.mj_footer           = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self laodmore];
    }];
    _mytable.mj_footer.hidden    = YES;
    MJHiCarHeader *header           = [MJHiCarHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadnew)];
    header.automaticallyChangeAlpha    = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden           = YES;
    _mytable.mj_header          = header;
    _mytable.mj_header.automaticallyChangeAlpha = YES;
    [_mytable.mj_header beginRefreshing];
    
    _bottomview = [[TouPiaoButtomView alloc] initWithFrame:CGRectMake(0,RECERHEIGHT-(NAV_Height-20), RECRWITCH, NAV_Height-25)];
    _bottomview.selectblock = ^(NSInteger type) {
        if (type==0) {
            [self zandian];
        }else if (type==1){
            [self gentieView];
        }else{
            [self godoneLike];
        }
    };
    _bottomview.Model=_Model;
    [self.view addSubview:_bottomview];
    
    @try {
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"LikeArray001"]) {
            [shuju recoverFormStateWithKey:@"LikeArray001"];
            _Like_list = shuju.JoneArray;
        }
        
        [_Like_list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LunTanModel *linmodel = (LunTanModel *)obj;
            if ([linmodel.lun_id isEqualToString:weakSelf.Model.lun_id]) {
                self->Like_OK = YES;
            }
        }];
        
        [self reload_bottom];
        
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
}

- (void)godoneLike{
    __weak __typeof(&*self)weakSelf = self;
    
    @try {
        if (Like_OK) {
            [_Like_list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                LunTanModel *linmodel = (LunTanModel *)obj;
                if ([linmodel.lun_id isEqualToString:weakSelf.Model.lun_id]) {
                    [self->_Like_list removeObjectAtIndex:idx];
                    *stop = YES;
                }
            }];
            Like_OK = NO;
        }else{
            if (_Like_list.count>0) {
                [_Like_list insertObject:_Model atIndex:0];
            }else{
                [_Like_list addObject:_Model];
            }
            Like_OK = YES;
        }
        
        JoneCunChu *shuju=[[JoneCunChu alloc] init];
        shuju.JoneArray=_Like_list;
        [shuju saveStateWithKey:@"LikeArray001"];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    [self reload_bottom];
}

- (void)reload_bottom{
    if (Like_OK) {
        [_bottomview.button03 setTitle:@"  已收藏" forState:UIControlStateNormal];
        [_bottomview.button03 setImage:[UIImage imageNamed:@"lun_shou_yes"] forState:UIControlStateNormal];
    }else{
        [_bottomview.button03 setTitle:@"  收藏" forState:UIControlStateNormal];
        [_bottomview.button03 setImage:[UIImage imageNamed:@"lun_shou_b"] forState:UIControlStateNormal];
    }
}


- (void)shanchu{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确认删除?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self shanchu_ok];
    }];
    [alertController addAction:sureAction];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}


-(void)shanchu_ok{
    [HJonesNetting JonesNetting_POST:@{@"user_id":[UserModel info].userid,@"l_id":_Model.lun_id}
                              andURL:@"AddWork/sahnchuluntan"
                          andtimeout:20.0
                            finished:^(NSError * _Nonnull error, NSDictionary * _Nonnull resultDict) {
                                if (error) {
                                    [SVProgressHUD showErrorWithStatus:@"网络加载失败"];
                                    
                                }else{
                                    if ([[resultDict objectForKey:@"Code"] longLongValue]==1000) {
                                        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"FABUCHNEGGONG" object:@{@"done":@"0"}];
                                        [self goback];
                                        
                                    }else{
                                        [SVProgressHUD showErrorWithStatus:[resultDict objectForKey:@"Message"]];
                                    }
                                }
                            }
                          passmanger:^(NSURLSessionDataTask * _Nonnull manger) {
                              
                          }
                         andprogress:^(NSProgress * _Nonnull CProgress) {
                             
                         }];
}

- (void)loadnew{
    page = 0;
    self.TableView.mj_footer.hidden    = YES;
    [self laod_net_dic];
}

- (void)laodmore{
    LunCommentModel *modellin = [self.Data_array lastObject];
    page = [modellin.lcomment_id integerValue];
    [self laod_net_dic];
}

- (void)laod_net_dic{
    NSMutableDictionary *postdic = [NSMutableDictionary new];
    [postdic setValue:[NSString stringWithFormat:@"%li",(long)page] forKey:@"page"];
    [postdic setValue:@"0" forKey:@"userid"];
    [postdic setValue:_Model.lun_id forKey:@"luntan_id"];
    GetLunCommnetVModel *viewmodel = [[GetLunCommnetVModel alloc] init:postdic];
    viewmodel.delegate = self;
}

- (void)GetCommentSucces:(int)value array:(NSMutableArray *)array page:(NSInteger)page{
    if (value == 1) {
        if (page==0) {
            id linmodel = [self.Data_array firstObject];
            [self.Data_array removeAllObjects];
            [self.Data_array addObject:linmodel];
        }
        [self.Data_array addObjectsFromArray:array];
        
        if (array.count<15) {
            _mytable.mj_footer.hidden = YES;
        }else{
            _mytable.mj_footer.hidden = NO;
        }
        _mytable.mj_header.hidden = YES;
    }
    [_mytable.mj_header endRefreshing];
    [_mytable.mj_footer endRefreshing];
    [_mytable reloadData];
}

- (void)gentieView{
    if (![UserModel info].userid) {
        [RootSuperAction Actiontodone:JonesGOTO_Login view:self dictionary:@{}];
        return;
    }
    
    GengTieView *linview = [GengTieView Show:CGRectMake(40, NAV_Height+10, RECRWITCH-80, RECERHEIGHT/2-100)];
    linview.Model = _Model;
    linview.Selectblock = ^(NSInteger type) {
        if (type==1) {
            [self loadnew];
        }
    };
}

- (void)zandian{
    if (![UserModel info].userid) {
        [RootSuperAction Actiontodone:JonesGOTO_Login view:self dictionary:@{}];
        return;
    }
    
//    if (Zan_ok) {
//        [SVProgressHUD showErrorWithStatus:@"您已点赞过"];
//        return;
//    }
    
    [HJonesNetting JonesNetting_POST:@{@"user_id":[UserModel info].userid,@"l_id":_Model.lun_id,@"type":@"0"}
                              andURL:@"AddWork/zanluntan"
                          andtimeout:20.0
                            finished:^(NSError * _Nonnull error, NSDictionary * _Nonnull resultDict) {
                                if (error) {
                                    [SVProgressHUD showErrorWithStatus:@"网络加载失败"];
                                    
                                }else{
                                    if ([[resultDict objectForKey:@"Code"] longLongValue]==1000) {
                                        
                                        Zan_ok = YES;
                                        
                                        NSInteger incdfsf = [self->_Model.zan_count integerValue] + 1;
                                        self->_Model.zan_count = [NSString stringWithFormat:@"%li",(long)incdfsf];
                                        [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
                                        [_bottomview.button01 setTitle:[NSString stringWithFormat:@"  点赞(%@)",self->_Model.zan_count] forState:UIControlStateNormal];
                                    }else{
                                        [SVProgressHUD showErrorWithStatus:[resultDict objectForKey:@"Message"]];
                                    }
                                }
                            }
                          passmanger:^(NSURLSessionDataTask * _Nonnull manger) {
                              
                          }
                         andprogress:^(NSProgress * _Nonnull CProgress) {
                             
                         }];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    HomeInfoTopheaderView *headerview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
//    headerview.Model = _Model;
//    headerview.selectblock = ^(NSInteger type) {
//        if (type==1) {
//            [self gentieView];
//        }else{
//            [self zandian];
//        }
//    };
//    return headerview;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return _Model.Height + 90;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.Data_array.count;
}

#pragma mark - UITableView DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeInfoTCell *cell = [HomeInfoTCell cellForTableView:tableView cellForRowAtIndexPath:indexPath];
    cell.supervsl = self;
    cell.Model = [self.Data_array objectAtIndex:indexPath.row];
    cell.Label_showtype.text = [NSString stringWithFormat:@"%ld楼",(long)indexPath.row];
    return cell;
}

#pragma mark - UITableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LunCommentModel *model = [self.Data_array objectAtIndex:indexPath.row];
    if (indexPath.row==0) {
        return model.Height + 110;
    }
    return model.Height + 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)fabu{
    UserJubuViewModel *actionjubao = [UserJubuViewModel show:self dic:@{@"userid":@"0",@"type":@"0",@"to_userid":@"0",@"to_id":@"10"}];
    actionjubao.selectblock = ^(BOOL type) {
        //        [weakSelf cunJubao];
    };
}

@end
